<template>
  <div>
    <div>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="2"
        :formType="type"
        labelWidth="110"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
      <el-form :model="ruleForm" ref="addRuleForm" label-width="110px" :rules="rules">
        <el-form-item label="跟进结果" prop="actionStatus" v-if="clueStatus !==70001011?true:false">
          <el-input v-model="ruleForm.actionStatus" style="display:none;"></el-input>
          <!-- 待定:70521001 流失:70521002 成功:70521003  -->
          <el-button :class="isBlue2" @click="selectBtn(70521001)">待定</el-button>
          <el-button :class="isBlue3" @click="selectBtn(70521002)">流失</el-button>
          <el-button :class="isBlue4" @click="selectBtn(70521003)">成功</el-button>
        </el-form-item>
        <el-form-item
          v-if="this.selectBtnNum == 70521001?true:false"
        >
        </el-form-item>
        <template
          v-else-if="this.selectBtnNum == 70521002?true:false"
        >
          <el-form-item label="失效车辆" prop="vin" class="unfireCar">
            <el-select v-model="ruleForm.vin" multiple collapse-tags>
              <el-option v-for="(item,k) of failedVehicle" :key="k" :label="item.text" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="流失原因" prop="resultReason">
            <el-select v-model="ruleForm.resultReason">
              <el-option v-for="(item,k) of lossCauses" :key="k" :label="item.text" :value="item.value"></el-option>
              <!-- <el-option label="流失原因二" value="beijing1"></el-option> -->
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="下次跟进时间" prop="nextActionedDate">
            <el-date-picker
              v-model="ruleForm.nextActionedDate"
              type="datetime"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item> -->
          <el-form-item label="下次跟进时间" prop="nextActionedDate">
            <el-date-picker
              v-model="ruleForm.nextActionedDate"
              type="date"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="下次跟进备注">
            <el-input type="textarea" v-model="ruleForm.taskName"></el-input>
          </el-form-item>
        </template>

        <!-- 成功 -->
        <template v-else-if="this.selectBtnNum == 70521003?true:false">
          <el-form-item label="下次跟进时间" prop="nextActionedDateA">

            <el-date-picker
              v-model="ruleForm.nextActionedDateA"
              type="date"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="下次跟进备注">
            <el-input type="textarea" v-model="ruleForm.taskName1"></el-input>
          </el-form-item>
        </template>
      </el-form>
    </div>
    <p style="height:25px;"></p>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button @click="closeDialog(false)">取 消</el-button>
      <el-button @click="saveDialog('addRuleForm')" :disabled="isDisabled" type="primary">保 存</el-button>
    </div>
  </div>
</template>

<script>
import {
  getFollowInfoById,
} from '@/api/potenCus/customer/customerFollowInfo';
import { queryFollowWays } from '@/api/potenCus/basedata/followWays';
import { dictionary } from '@/utils/dictMixin';
import { formatDates } from '@/utils/validate';
import { plateUndeterminedClue,plateLossClue,plateSuccessClue,getPlateDistCarList } from '@/api/potenCus/basePlate/basePlateFollow/index';
import { formatdate} from '@/utils/index';
import { getIntentLevelsList } from '@/api/potenCus/customer/potenCusManage';
import {
  searchInvalidClues,
 } from '@/api/potenCus/basedata/custTaskOEM';
export default {
  name: 'mModal',
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'edit'
    },
    baseType: {
      type: String,
      default: ''
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    accordingObj() {
      return (
        this.selectBtnNum == 70521001 &&
        Object.keys(this.according2ReasonObj)
          .map(item => Number(item))
          .includes(this.ruleForm.resultReason)
      );
    }
  },
  data() {
    this.saveData = null;
    return {
      isBlue: '',
      isBlue1: '',
      isBlue2: '',
      isBlue3: '',
      isBlue4: '',
      clueStatus: '',
      ruleForm: {
        actionStatus: '', //跟进结果
        nextActionedDate: '', //下次跟进时间
        nextActionedDateA: '', //下次跟进时间
        vin:"",
        resultReason:"",
        taskName: '', //跟进备注
        taskName1: '', //跟进备注
        invitationsDate: '', //预约时间
        resultReason: '', //战败原因
        actionDate: '',
        defeatReasonsIdOne: '', // 根据战败原因按需显示
        defeatReasonsIdTwo: '' // 根据战败原因按需显示
      },
      rules: {
        actionStatus: [{ required: true, message: '请选择跟进结果', trigger: 'blur' }],
        invalidReason: [{ required: true, message: '请选择无效原因', trigger: 'blur' }],
        nextActionedDate: [{ required: true, message: '请选择下次跟进时间', trigger: 'blur' }],
        nextActionedDateA: [{ required: true, message: '请选择下次跟进时间', trigger: 'blur' }],
        resultReason: [{ required: true, message: '请选择战败原因', trigger: 'blur' }],
        invitationsDate: [{ required: true, message: '请选择预约时间', trigger: 'blur' }],
        vin: [{ required: true, message: '请选择', trigger: 'change' }],
        resultReason: [{ required: true, message: '请选择', trigger: 'change' }],
      },
      isDisabled: false, //表单重复提交
      invalidReasonList: [],
      defeatReasonList: [],
      formList: this.createFormList(),
      page: {
        pageNum: 1,
        currentPage: 1,
        pageSize: 100,
        limit: 100,
        isValid: 10041001
      },
      dealerPage: {
        currentPage: 1,
        pageSize: 10000
      },
      selectBtnNum: 0,
      clueType: '',
      listAllData:[],
      lossCauses:[],
      failedVehicle:[],
    };
  },
  watch: {
    ruleForm() {
      console.log(this.ruleForm.actionStatus,"ruleForm.actionStatus")
      if (this.ruleForm.actionStatus == 70521001) {
        this.isBlue2 = 'isBlue';
      } else if (this.ruleForm.actionStatus == 70521002) {
        this.isBlue3 = 'isBlue';
      } else if (this.ruleForm.actionStatus == 70521003) {
        this.isBlue4 = 'isBlue';
      }
    },

  },
  created() {
    this.init();
    this.ordinaryYear()
  },
  methods: {
    async init() {
        this.formList.forEach(x=>{
          x.initialValue = this.rowData[x.fieldName]
        })
        console.log(this.rowData,"this.rowData")
        Object.keys(this.ruleForm).forEach(x=>{
          this.ruleForm[`${x}`]=this.rowData[x]
        })
        this.formList.find(x=>x.fieldName == 'level').initialValue = Number(this.rowData['level'])
        // console.log(this.formList.find(x=>x.fieldName == 'purposeReturn').initialValue,"跟进目的")
        let arr=[]
        if(this.formList.find(x=>x.fieldName == 'purposeReturn').initialValue){
          this.formList.find(x=>x.fieldName == 'purposeReturn').initialValue.split(",").forEach(x=>{
            arr.push(x)
            // console.log(arr,"456")
          })
        }
        this.formList.find(x=>x.fieldName == 'purposeReturn').initialValue = arr
        if(this.rowData['planActionDate']){
          console.log(this.rowData['planActionDate'],"this.rowData['planActionDate']")
          if(this.rowData['planActionDate'] > 100000000){
            this.formList.find(x=>x.fieldName == 'planActionDate').initialValue = formatDates(this.rowData['planActionDate'])
          }else{
            this.formList.find(x=>x.fieldName == 'planActionDate').initialValue = this.rowData['planActionDate'].split(" ")[0]
          }
        }
        // 待定:70521001 无效:70521002 成功:70521003
          // console.log(this.rowData.actionStatus,this.rowData,"ruleForm.actionStatus")
          this.selectBtnNum=this.rowData.actionStatus
          if (this.rowData.actionStatus == 70521001) {
            this.isBlue2 = 'isBlue';
          } else if (this.rowData.actionStatus == 70521002) {
            this.isBlue3 = 'isBlue';
          } else if (this.rowData.actionStatus == 70521003) {
            this.isBlue4 = 'isBlue';
          }
      //
      let params={
        potentialCustomerId:this.rowData.potentialCustomerId?this.rowData.potentialCustomerId:this.rowData.potentialCustomersId
      }
      // console.log(params,"params",this.rowData)
      getPlateDistCarList(params).then(res=>{
        // console.log(res,"res")
        if(res.resultCode == 200){
          //带有数据后处理
          res.data.forEach(x=>{
            this.failedVehicle.push({ value: x.soVinId, text: x.productConfig })
          })
        }
      })
      // console.log(this.createDictList('7055'),"this.createDictList('7055')")
      this.lossCauses=this.createDictList('7055')
      //跟进方式
      this.getFollowInfo()
    },
    //判断年份
    async ordinaryYear(){
      const res = await searchInvalidClues()
      let intervalDays = ""
      res.data.forEach(x=>{
        if(x.intentLevel == this.formList.find(x=>x.fieldName == 'level').initialValue){
          console.log(x.intervalDays,"天数")
          intervalDays=x.intervalDays
        }
      })

      let oddNumber = [1,3,5,7,8,10,12]
      let evenNumber = [4,6,9,11]
      let y = new Date()
      let year = y.getFullYear()
      let month = y.getMonth()+1
      let day = y.getDay()
      let h = y.getHours()
      let m = y.getMinutes()
      console.log(year,month,day,h,m,"当前时间")

      let nextYear = 0
      let nextYear2 = 0
      let nextMonth = 0
      let nextMonth2 = 0
      let nextDay = 0
      let nextDay2=0
      let nextH = 0
      let nextM = 0


      // 成功 nextActionedDateA  流失 nextActionedDate
      console.log('意向', this.ruleForm.nextActionedDate,this.ruleForm.nextActionedDateA)
      /* if(year/4 == 0 && year/100!=0 || year/400 == 0){
        console.log("闰年")
  　　}else{ */
  　　    console.log("平年",intervalDays)
          oddNumber.forEach(x=>{
            if(month == x){
              console.log(x,"偶数")
              if(month == x){
                nextYear = year
                nextMonth = month
                nextDay = day + intervalDays
                nextH = h
                nextM = m

                if(nextDay > 31){
                  // 日
                  let dateString = String(nextDay/31)
                  console.log(dateString)
                  let dateNum = Number(dateString.split(".")[0])
                      nextDay2=nextDay-dateNum*31
                      nextMonth+=dateNum
                  console.log(nextDay2,"偶数nextDay",nextMonth)
                  if(nextMonth > 12){
                    // 月
                    nextYear++
                    nextMonth2 = nextMonth - 12
                    console.log(nextMonth,"偶数nextMonth")
                  }
                }
              }
            }
          })

          evenNumber.forEach(x=>{
            if(month == x){
              console.log(x,"奇数")
              if(month == x){
                nextYear = year
                nextMonth = month
                nextDay = day + intervalDays
                nextH = h
                nextM = m

                if(nextDay > 30){
                  // 日
                  let dateString = String(nextDay/30)
                  console.log(dateString)
                  let dateNum = Number(dateString.split(".")[0])
                      nextDay2=nextDay-dateNum*30
                      nextMonth+=dateNum
                  console.log(nextDay2,"奇数nextDay",nextMonth)
                  if(nextMonth > 12){
                    // 月
                    nextYear++
                    nextMonth2 = nextMonth - 12
                    console.log(nextMonth,"奇数nextMonth")
                  }
                }
              }
            }
          })

          /* if(month == 2){
            console.log(x,"2月")
              nextYear = year
              nextMonth = month
              nextDay = day + intervalDays
              nextH = h
              nextM = m

              if(nextDay > 30){
                // 日
                let dateString = String(nextDay/30)
                console.log(dateString)
                let dateNum = Number(dateString.split(".")[0])
                    nextDay2=nextDay-dateNum*30
                    nextMonth+=dateNum
                console.log(nextDay2,"奇数nextDay",nextMonth)
                if(nextMonth > 12){
                  // 月
                  nextYear++
                  nextMonth2 = nextMonth - 12
                  console.log(nextMonth,"奇数nextMonth")
                }
              }
          } */
      //}
        console.log(nextYear,nextMonth2,nextDay2,nextH,nextM,"当前时间2")
        this.ruleForm.nextActionedDate = new Date(nextYear,nextMonth2-1,nextDay2,nextH,nextM)
        this.ruleForm.nextActionedDateA = new Date(nextYear,nextMonth2-1,nextDay2,nextH,nextM)
    },
    selectChangeHandle(rows) {
      if (!rows.length) return;
      this.selectedRow = rows[0];
    },
    createFormList() {
      return [
        {
          type: 'DATE',
          label: '计划跟进时间',
          fieldName: 'planActionDate',
          disabled: true,
          initialValue: '',
          selfCols: 2,
          placeholder: '计划跟进时间',
          dateType:"exactdate",
          valueFormat: 'yyyy-MM-dd',
        },
        {
          type: 'TEXT_AREA',
          label: '跟进备注',
          fieldName: 'taskName',
          selfCols: 2,
          disabled: true,
          placeholder: ''
        },

        {
          type: 'SELECT',
          label: '客户等级',
          fieldName: 'level',
          placeholder: '请选择',
          initialValue: '',
          // itemList: [{ value: 15191001, text: 'A' }, { value: 15191002, text: 'B' }, { value: 15191003, text: 'C' }, { value: 15191010, text: 'H' }],
          itemList:this.createDictList('7049') ,
          disabled: true,
          rules: [{ required: true, message: '请选择客户等级', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '跟进方式',
          fieldName: 'actionedWay',
          placeholder: '请选择',
          initialValue: undefined,
          itemList: [],
          hidden: false,
          rules: [{ required: true, message: '请选择跟进方式', trigger: 'blur' }]
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '跟进目的',
          fieldName: 'purposeReturn',
          placeholder: '请选择',
          selfCols: 2,
          itemList: [
            { value: "70541001", text: '年检提醒' },
            { value: "70541002", text: '定保提醒' },
            { value: "70541003", text: '续保提醒' },
          ]
        },
        {
          type: 'TEXT_AREA',
          label: '本次跟进情形',
          fieldName: 'scene',
          selfCols: 2,
          placeholder: '请输入'
        }
      ];
    },

    selectBtn(num) {
      this.selectBtnNum = num;
      this.isBlue = '';
      this.isBlue1 = '';
      this.isBlue2 = '';
      this.isBlue3 = '';
      this.isBlue4 = '';
      this.ruleForm.actionStatus = num;
      if (this.ruleForm.actionStatus == 15171009) {
        this.isBlue = 'isBlue';
      } else if (this.ruleForm.actionStatus == 15171007) {
        this.isBlue1 = 'isBlue';
      } else if (this.ruleForm.actionStatus == 70521001) {
        this.isBlue2 = 'isBlue';
      } else if (this.ruleForm.actionStatus == 70521002) {
        this.isBlue3 = 'isBlue';
      } else if (this.ruleForm.actionStatus == 70521003) {
        this.isBlue4 = 'isBlue';
      }
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    // 获取跟进明细
    async getFollowInfo() {
      //const res = await getFollowInfoById(this.recordId);
      console.log('跟进明细');
      this.getFollowWays();
      // if (res.resultCode === 200) {
      //   this.formList.forEach(x => {
      //     if (x.fieldName === 'businessAnally') {
      //       x.initialValue = res.data[x.fieldName] ? res.data[x.fieldName].split(',').map(x => parseInt(x)) : [];
      //     } else {
      //       x.initialValue = res.data[x.fieldName];
      //     }
      //   });
      //   this.clueStatus = res.data.clueStatus;
      //   this.clueType = res.data.clueType;
      // }
    },




    // 跟进方式
    async getFollowWays() {
      const res = await queryFollowWays(this.page);
      // console.log('跟进方式',res)
      if (res.resultCode === 200) {
        let waysData = res.data.records;
        this.formList.find(item => item.fieldName === 'actionedWay').itemList = waysData.map(x => ({ value: x.basedataId, text: x.basedataName }));
        // waysData.forEach(x => {
        //   if (x.basedataName == '电话') {
        //     this.formList.find(item => item.fieldName === 'actionedWay').initialValue = x.basedataId;
        //   }
        // });
      }
    },

    saveDialog(formName) {

      this.$refs.formPanel.SUBMIT_FORM();
      this.$refs[formName].validate(valid => {
        if (valid && this.$refs.formPanel.SUBMIT_FORM()) {
          this.save();
        } else {
          // this.$message.info('请填写必填项!');
          return false;
        }
      });
    },
    async save() {
      this.isDisabled =true
      // if (this.ruleForm.nextActionedDateA) {
      //   this.ruleForm.nextActionedDate = new Date(this.ruleForm.nextActionedDateA).getTime();
      // } else {
      //   this.ruleForm.nextActionedDate = new Date(this.ruleForm.nextActionedDate).getTime();
      // }
      console.log(this.ruleForm,this.saveData,"this.saveData",this.rowData)
      let actionId = this.rowData.actionId
      if(this.baseType == "fail"){
        actionId = this.rowData.detailActionId
      }
      let saveObj = { ...this.ruleForm, ...this.saveData,actionId:actionId,basalOrderId:"",potentialCustomersId:this.rowData.potentialCustomerId?this.rowData.potentialCustomerId:this.rowData.potentialCustomersId};

      if(saveObj.nextActionedDate){
        saveObj.nextActionedDate = Date.parse(saveObj.nextActionedDate)
      }else{
        saveObj.nextActionedDate = null
      }

      if(saveObj.nextActionedDateA){
        saveObj.nextActionedDateA = Date.parse(saveObj.nextActionedDateA)
      }else{
        saveObj.nextActionedDateA = null
      }

      if(saveObj.planActionDate){
          saveObj.planActionDate = Date.parse(saveObj.planActionDate)
      }else{
          saveObj.planActionDate = null
      }

      if(this.ruleForm.taskName){
        saveObj.taskName =this.ruleForm.taskName
      }

      // 待定:70521001 无效:70521002 成功:70521003
      if(saveObj.purposeReturn){
          if(saveObj.purposeReturn.length > 0){
              let arr=""
              saveObj.purposeReturn.forEach(x=>{
                arr+=x+","
                saveObj.purposeReturn=arr
              })
          }else{
            saveObj.purposeReturn=""
          }
      }
      saveObj.basalOrderId=saveObj.vin.toString()
      console.log(this.selectBtnNum,"this.selectBtnNum",saveObj)
      // 待定
      if(this.selectBtnNum == 70521001){
        plateUndeterminedClue(saveObj)
        .then(res => {
          this.isDisabled = false;
          if (res.resultCode === 200) {
            this.closeDialog('refresh');
            this.$message.success('保存成功!');
          } else {
            // this.$message.info('请填写必填项');
            return false;
          }
        })
        .catch(err => {
          // this.$message.info(err.errMsg);
          this.isDisabled = false;
        });
      }else if(this.selectBtnNum == 70521002){
        // 流失
          plateLossClue(saveObj)
        .then(res => {
          this.isDisabled = false;
          if (res.resultCode === 200) {
            this.closeDialog('refresh');
            this.$message.success('保存成功!');
          } else {
            // this.$message.info('请填写必填项');
            return false;
          }
        })
        .catch(err => {
          // this.$message.info(err.errMsg);
          this.isDisabled = false;
        });
      }else if(this.selectBtnNum == 70521003){
        // 成功
        saveObj.taskName=saveObj.taskName1
        saveObj.nextActionedDate=saveObj.nextActionedDateA
        plateSuccessClue(saveObj)
        .then(res => {
          this.isDisabled = false;
          if (res.resultCode === 200) {
            this.closeDialog('refresh');
            this.$message.success('保存成功!');
          } else {
            // this.$message.info('请填写必填项');
            return false;
          }
        })
        .catch(err => {
          // this.$message.info(err.errMsg);
          this.isDisabled = false;
        });
      }
    },
    closeDialog(param) {
      this.$emit('close', param);
    },

  }
};
</script>

<style lang="less">
.isBlue {
  background: #ecf5ff;
}
.unfireCar{
  .el-select{
    width:70%
  }
}
</style>
